package com.hetang.maijiayun.adaptertools.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.text.DateFormat;
import java.util.Arrays;

public class Util {
	public static String concat(String[] arr, Integer len, String seperator) {
		if(len == 0)
			return "";
		
		StringBuilder sb = new StringBuilder(len * 3);
		int offset = len - 1;
		for( int i = 0; i < offset; i++ )
		    sb.append(arr[i]).append(seperator);
		sb.append(arr[offset]);
		return sb.toString();		
	}
	
	public static String propertyToB2cIdentifier(String b2cIdentifier, String properties) throws AdapterException {
		if(properties == null || properties.isEmpty())
			return "";
		
		String[] props = properties.split(";");
		String[] arr = new String[props.length];
		int i = 0;
		for(String prop : props) {
			String[] pair = prop.split(":");
			if(pair.length != 2)
				throw new AdapterException(AdapterExceptionErrorCode.B2C_RPC_PARAS_ERROR_CODE, "properties format errror properties : " + properties);
			arr[i] = b2cIdentifier + "|" + pair[0] + ":" + b2cIdentifier + "|" + pair[1];
			i++;
		}
		
		return Util.sortConcat(arr, ";");
	}
	
	public static String[] arrayCopy(String[] oldArr, int size) throws AdapterException {
		if(oldArr == null)
			return null;
		if(size > oldArr.length)
			throw new AdapterException(AdapterExceptionErrorCode.B2C_RPC_PARAS_ERROR_CODE, "size is larger than oldArr length");	
		String[] newArr = new String[size];
		for(int i = 0; i < size; i++)
			newArr[i] = oldArr[i];
		return newArr;
	}

	public static String[] arrayCopy(String[] oldArr, int startIndex, int size) throws AdapterException {
		if(oldArr == null)
			return null;
		if(startIndex + size > oldArr.length)
			throw new AdapterException(AdapterExceptionErrorCode.B2C_RPC_PARAS_ERROR_CODE, "size is larger than oldArr length");	
		String[] newArr = new String[size];
		for(int i = startIndex; i < size; i++)
			newArr[i] = oldArr[i];
		return newArr;
	}
	
	public static String codeFromIdentifier(String htCode) throws AdapterException {
		String[] codes = htCode.split("\\|");
		if(codes.length < 2)
			throw new AdapterException(AdapterExceptionErrorCode.B2C_RPC_PARAS_ERROR_CODE, "rawCode length error - code : " + htCode);
		return codes[1];
	}
	
	public static String codeToIdentifier(String b2cIdentifier, String b2cCode) throws AdapterException {
		return b2cIdentifier + "|" + b2cCode;
	}	

	public static String sortConcat(String[] arr, Integer len, String seperator) {
		Arrays.sort(arr);
		StringBuilder sb = new StringBuilder(len * 3);
		int offset = arr.length - 1;
		for( int i = 0; i < offset; i++ )
		    sb.append(arr[i]).append(seperator);
		sb.append(arr[offset]);
		return sb.toString();		
	}
	
	public static String inputStream2String(InputStream is) throws AdapterException {
		BufferedReader in = new BufferedReader(new InputStreamReader(is));
		StringBuffer buffer = new StringBuffer();
		String line = "";
		   
		try {
			while ((line = in.readLine()) != null){
				buffer.append(line);
			}
		} catch(IOException ie) {
			throw new AdapterException(AdapterExceptionErrorCode.B2C_RPC_ERROR_CODE, ie.getMessage());
		}
		return buffer.toString();
	}
	public static String inputStream2String(InputStream is,String charSet) throws AdapterException {
        BufferedReader in= null;
        try {
            in = new BufferedReader(new InputStreamReader(is,charSet));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new AdapterException(AdapterExceptionErrorCode.B2C_RPC_ERROR_CODE, e.getMessage());
        }
        StringBuffer buffer = new StringBuffer();
        String line = "";
           
        try {
            while ((line = in.readLine()) != null){
                buffer.append(line);
            }
        } catch(IOException ie) {
            throw new AdapterException(AdapterExceptionErrorCode.B2C_RPC_ERROR_CODE, ie.getMessage());
        }
        return buffer.toString();
    }
	
	public static<T> String getCommandName(Class<T> clazz) {
		String[] paths = clazz.getName().split("\\.");
		return paths[paths.length - 1];
	}
	
	public static String sortConcat(String[] arr, String seperator) {
		return sortConcat(arr, arr.length, seperator);
	}
	
	public static String concat(String[] arr, String seperator) {
		return concat(arr, arr.length, seperator);
	}
	
	public static Date strToDate(String str, DateFormat format) throws AdapterException {
		try {
			return format.parse(str);
		} catch(ParseException pe) {
			throw new AdapterException(AdapterExceptionErrorCode.ADAPTER_PARAS_ERROR_CODE, "string can not be converted to Date str : " + str);
		}
	}

	public static Date strToDate(String str) throws AdapterException {
		try {
			DateFormat format = new SimpleDateFormat(DATE_FORMAT);
			return format.parse(str);
		} catch(ParseException pe) {
			throw new AdapterException(AdapterExceptionErrorCode.ADAPTER_PARAS_ERROR_CODE, "string can not be converted to Date str : " + str);
		}
	}
	
	public static String dateToStr(Date dt, DateFormat df) throws AdapterException {
		return df.format(dt);
	}
	
	public static String dateToStr(Date dt) throws AdapterException {
		DateFormat format = new SimpleDateFormat(DATE_FORMAT);
		return format.format(dt);
	}
	
	/*public static Date strToDateDefaultNow(String str, DateFormat format) throws AdapterException {
		if(str == null)
			return new Date();
		
		try {
			return format.parse(str);
		} catch(ParseException pe) {
			return new Date();
		}
	}*/
	
	public static Date strToDateDefaultNow(String str) throws AdapterException {
		if(str == null)
			return new Date();
		
		try {
			DateFormat format = new SimpleDateFormat(DATE_FORMAT);
			return format.parse(str);
		} catch(ParseException pe) {
			return new Date();
		}
	}
	
	public static String stringIfNullEmpty(String t) {
		if(t == null)
			return "";
		else
			return t;
	}
	
	public static Boolean booleanIfNullFalse(Boolean t) {
		if(t == null)
			return false;
		else
			return t;
	}
	
	public static BigDecimal bigDecimalIfNullZero(BigDecimal t) {
		if(t == null)
			return new BigDecimal(0);
		else
			return t;
	}
	
	public static Date dateIfNullNow(Date t) {
		if(t == null)
			return new Date();
		else
			return t;
	}
	
	public static Integer integerIfNullZero(Integer t) {
		if(t == null)
			return 0;
		else
			return t;
	}
	
	public static Integer stringToIntegerIfNullZero(String t) {
		if(t == null)
			return 0;
		else
			return Integer.parseInt(t);
	}
	
	public static Long stringToLongIfNullZero(String t) {
		if(t == null)
			return 0L;
		else
			return Long.parseLong(t);
	}
	
	public static BigDecimal stringToBigDecimalIfNullToZero(String t) {
		if(t == null)
			return new BigDecimal(0);
		else
			return new BigDecimal(t);
	}
	
	public static enum OrderStatus {
		 WAIT_FOR_BUYER_PAY(0), WAIT_FOR_CHECK(1), 
		 WAIT_FOR_DELIVERY(2), STOCK_OUT(3), CANCEL(4), FINISHED(5);
		 
		 private int value;
		 
		 private OrderStatus(int value) {
			 this.value = value;
		 }
		 
		 public String toString() {
			 return Integer.toString(value);
		 }
		 
		 public Boolean isMore(OrderStatus status) {
			 if(status == null)
				 return true;
			 return value > status.value;
		 }
	}
	
	public static HashMap<String, OrderStatus> OrderStatusMapping = new HashMap<String, OrderStatus>(){
		private static final long serialVersionUID = 1L;
		{
			put("待付款", OrderStatus.WAIT_FOR_BUYER_PAY);
			put("已付款待审核", OrderStatus.WAIT_FOR_CHECK);
			put("已审核待发货", OrderStatus.WAIT_FOR_DELIVERY);
			put("已发货", OrderStatus.STOCK_OUT);
			put("已取消", OrderStatus.CANCEL);
			put("已完成", OrderStatus.FINISHED);
		}
	};
	
	public static enum ReturnBillStatus {
		 WAIT_FOR_SELLER_AGREE(0), CONFIRM(1), REFUSE(2);
		 
		 private int value;
		 
		 private ReturnBillStatus(int value) {
			 this.value = value;
		 }
		 
		 public String toString() {
			 return Integer.toString(value);
		 }
		 
		 public Boolean isMore(ReturnBillStatus status) {
			 if(status == null)
				 return true;
			 return value > status.value;
		 }
	}
	
	public static HashMap<String, ReturnBillStatus> ReturnBilllStatusMapping = new HashMap<String, ReturnBillStatus>(){
		private static final long serialVersionUID = 1L;
		{
			put("待审核", ReturnBillStatus.WAIT_FOR_SELLER_AGREE);
			put("已同意", ReturnBillStatus.CONFIRM);
			put("已拒绝", ReturnBillStatus.REFUSE);
		}
	};
	
	public static Date secondToDate(Long second) {
		GregorianCalendar gc = new GregorianCalendar(); 
        gc.setTimeInMillis(second * 1000);
        return gc.getTime();        
	}
	
	public static Long dateToSecond(Date dt) {
		if(dt.getTime() % 1000 == 0)
			return dt.getTime() / 1000;
		else
			return dt.getTime() / 1000 + 1;
	}
	
	public static String ONLINE_PAYMENT = "在线付款";
	public static String RECEIVED_PAYMENT = "货到付款";
	public static String BOOKING_PAYMENT = "预售";
	
	public static Long SUPER_USER = -1L;
	public static String INITIAL_TIME = "2000-01-01 00:00:00";
	public static String MAX_TIME = "2200-01-01 00:00:00";
	public static String SUCCESS = "成功";
	public static String FAILTURE = "失败";
	public static String PLATFORM_NEW_ADD = "add";
	public static String PLATFORM_UPDATE = "update";
	public static String PLATFORM_DELETE = "delete";
	public static String KAFKA_CONSUMER_PROPERTYIES = "kafkaConsumer.properties";
	
	public static String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
	
	//public static String CREATE_ORDER_STATUS = "订单创建";
	public static String HASPAYED_ORDER_STATUS = "已付款";
	
	public static String TRADING_FROZEN_SYNC = "TRADING_FROZEN_SYNC";
	public static String PAYMENT_FROZEN_SYNC = "PAYMENT_FROZEN_SYNC";
	public static String QUANTITY_SYNC = "QUANTITY_SYNC";
	
	public static String JINGDONG_SOP = "SOP";
	public static String JINGDONG_LBP = "LBP";
	public static String JINGDONG_SOPL = "SOPL";
	
	public static String SHUTDOWN_HOOK_KEY = "SHUTDOWN_HOOK_KEY";
}